import random
import re
from .._register import register_command
from ..sb_id.sb_text import load_alpha_table

@register_command("/id", "/火星文")
async def sb_id_command(client):
    args = client.msg.split(" ")
    if len(args) < 2:
        await client.reply("请输入要转换的文字~")
        return True

    alpha = load_alpha_table()

    # 检查最后一个参数是不是倍率
    multiplier = 1
    last_arg = args[-1]
    match = re.match(r"x(\d+)$", last_arg, re.IGNORECASE)
    if match:
        multiplier = min(int(match.group(1)), 15)
        text = args[1:-1]
    else:
        text = args[1:]

    if not text:
        await client.reply("请输入要转换的文字~")
        return True

    result_text = "\n"

    for _ in range(multiplier):
        converted_words = []
        for word in text:
            chars = []
            prev_type = None
            for i, ch in enumerate(word):
                base = ch.lower()
                if base in alpha:
                    # 如果是字母，保持原有 top/middle/bot 逻辑
                    if base.isalpha():
                        types = ['top','middle_s','middle_l','bot']
                        if prev_type in ['top','bot']:
                            types = [t for t in types if t != prev_type]
                        # 首字母强制 middle_l
                        if i == 0:
                            t = 'middle_l'
                            if not alpha[base][t]:
                                fallback = ['middle_s','top','bot']
                                t = random.choice(fallback)
                        else:
                            t = random.choice(types)
                            if not alpha[base][t]:
                                fallback = [x for x in types if alpha[base][x]]
                                t = random.choice(fallback) if fallback else None
                                if not t:
                                    chars.append(ch)
                                    prev_type = None
                                    continue
                        styled = random.choice(alpha[base][t])
                        prev_type = t
                    else:  # 数字或其他统一列表
                        styled = random.choice(alpha[base])
                        prev_type = None
                    chars.append(styled)
                else:
                    chars.append(ch)
                    prev_type = None
            converted_words.append("".join(chars))
        result_text += " ".join(converted_words) + "\n"

    result_text = result_text.strip()
    await client.reply(result_text or "（空文本）")
    return True
